<template>
  <div class="answer-container">
    <!-- Adding BackHeader like in learning.vue -->
    <back-header
      :customBack="customBack"
      :title="route.query.title ? route.query.title : '试卷回顾'"
      :titleSize="16"
      :titleBold="false"
    >
      <template #icon>
        <van-icon name="notes-o" size="24" />
      </template>
    </back-header>

    <div style="height: 56px"></div>

    <!-- Loading state -->
    <van-loading v-if="loading" class="loading-overlay" size="24px" vertical>
      加载中...
    </van-loading>

    <div v-else class="content">
      <div class="center_content" ref="centerContent">
        <div class="question-title">
          <span>{{ index + 1 }}.{{ item.question }}</span>
        </div>

        <!-- 单选题 -->
        <van-radio-group
          v-model="selectedRatio"
          v-show="item.answer.length == 1"
          class="option-group"
        >
          <div class="option-item">
            <van-radio name="A" @click="radioHandler">{{
              item.item1
            }}</van-radio>
          </div>
          <div class="option-item">
            <van-radio name="B" @click="radioHandler">{{
              item.item2
            }}</van-radio>
          </div>
          <div class="option-item">
            <van-radio name="C" @click="radioHandler">{{
              item.item3
            }}</van-radio>
          </div>
          <div v-if="item.item4" class="option-item">
            <van-radio name="D" @click="radioHandler">{{
              item.item4
            }}</van-radio>
          </div>
        </van-radio-group>

        <!-- 多选题 -->
        <van-checkbox-group
          v-model="selectedChecked"
          v-show="item.answer.length > 1"
          class="option-group"
        >
          <div class="option-item">
            <van-checkbox name="A" shape="square" @click="checkHandler">{{
              item.item1
            }}</van-checkbox>
          </div>
          <div class="option-item">
            <van-checkbox name="B" shape="square" @click="checkHandler">{{
              item.item2
            }}</van-checkbox>
          </div>
          <div class="option-item">
            <van-checkbox name="C" shape="square" @click="checkHandler">{{
              item.item3
            }}</van-checkbox>
          </div>
          <div v-if="item.item4" class="option-item">
            <van-checkbox name="D" shape="square" @click="checkHandler">{{
              item.item4
            }}</van-checkbox>
          </div>
        </van-checkbox-group>

        <!-- 答案解析 -->
        <div v-show="item.remark" class="answer-analysis">
          <van-divider>答案解析</van-divider>
          <p>{{ item.remark }}</p>
        </div>
      </div>

      <!-- 题目选择区弹窗 -->
      <van-popup
        v-model:show="questionSelectorVisible"
        position="bottom"
        :style="{ height: '60%' }"
        round
        closeable
      >
        <div class="question-selector-popup">
          <div class="popup-title">题目选择</div>
          <div class="legend">
            <div class="legend-item">
              <div class="legend-box correct"></div>
              <span>答对</span>
            </div>
            <div class="legend-item">
              <div class="legend-box incorrect"></div>
              <span>答错</span>
            </div>
            <div class="legend-item">
              <div class="legend-box current"></div>
              <span>当前题</span>
            </div>
          </div>
          <div class="question-grid">
            <div
              v-for="(_, i) in items"
              :key="i"
              class="question-box"
              :class="{
                correct: isCorrect(i),
                incorrect: isAnswered(i) && !isCorrect(i),
                current: i === index,
              }"
              @click="selectQuestion(i)"
            >
              {{ i + 1 }}
            </div>
          </div>
        </div>
      </van-popup>

      <!-- 功能按钮区域 - 更简洁的布局 -->
      <van-action-bar safe-area-inset-bottom style="height: 8vh">
        <van-action-bar-icon
          @click="toggleQuestionSelector"
          color="#3388ff"
          icon="apps-o"
          text="题目"
        />
        <van-action-bar-icon
          @click="showAnswer"
          color="#ff0000"
          :icon="showAnswerIcon"
          text="答案"
        />
        <van-field
          v-model="nowIndex"
          style="width: 30px; background-color: #f0f8ff"
          type="digit"
          :min="1"
          :max="total"
        />
        <span style="font-size: 13px; margin-left: 5px">/{{ total }}</span>
        <van-action-bar-icon
          icon="share-o"
          color="#29B6F6"
          @click="changeIndex(parseInt(nowIndex))"
          text="跳转"
        />
        <van-action-bar-button
          class="prev-button"
          @click="prev"
          text="上一题"
        />
        <van-action-bar-button
          class="next-button"
          @click="next"
          text="下一题"
        />
      </van-action-bar>
    </div>
  </div>
</template>

<script setup>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
import showAnswerIcon from "@/assets/showAnswer.png";
import BackHeader from "@/components/common/BackHeader.vue";
import zhiZhaoApi from "@/api/questionItem/questionItem";
import selfTest from "@/api/selfTest"; // 添加 selfTest 导入
import selfTestAnswer from "@/api/selfTest/selfTestAnswer"; // 添加 selfTestAnswer 导入
import store from "@/store";
import { ref, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showToast, showNotify } from "vant";

const route = useRoute();
const show = ref(false);
const index = ref(0);
const total = ref(0);
const items = ref([]); //所有的题
const item = ref({
  subject: "",
  question: "",
  item1: "",
  item2: "",
  item3: "",
  item4: "",
  answer: "",
}); //单独的某一道题
const selectedRatio = ref(""); //选择单选题的答案
const selectedChecked = ref([]); //选择多选题的答案
const allAnswers = ref([]); //选择的所有题目的答案
const questionStatus = ref([]); // 添加问题状态数组
const feedback = ref(false);
const nowIndex = ref(1);
const loading = ref(true);
const reviewPage = ref(false); // 是否回顾模式

// 题目选择弹窗状态
const questionSelectorVisible = ref(false);

// 切换题目选择器显示状态
const toggleQuestionSelector = () => {
  questionSelectorVisible.value = !questionSelectorVisible.value;
};

// 选择题目
const selectQuestion = (questionIndex) => {
  index.value = questionIndex;
  questionSelectorVisible.value = false; // 选择后关闭弹窗
};

const customBack = () => {
  if (!reviewPage.value) {
    router.push("/test/myexams");
  } else {
    router.push("/learning");
  }
};

watch(index, async (newVal) => {
  nowIndex.value = newVal + 1;
  selectedRatio.value = "";
  selectedChecked.value = [];
  item.value = items.value[newVal];

  const res = allAnswers.value[newVal].filter((a) => a != "");
  if (items.value[newVal].answer.length > 1) {
    //多选题
    selectedChecked.value = res;
  } else {
    //单选题
    selectedRatio.value = res[0];
  }
});

const compare = (array, str) => {
  if (array.length == 1) {
    return array[0] == str;
  } else {
    let arr = "";
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      arr += element;
      if (index < array.length - 1) {
        arr += "+";
      }
    }
    return arr == str;
  }
};

const changeIndex = (item) => {
  index.value = item - 1;
};

const setAllAnswers = (item) => {
  switch (item) {
    case "A":
      allAnswers.value[index.value][0] = item;
      break;
    case "B":
      allAnswers.value[index.value][1] = item;
      break;
    case "C":
      allAnswers.value[index.value][2] = item;
      break;
    case "D":
      allAnswers.value[index.value][3] = item;
      break;
    default:
      break;
  }
};

const radioHandler = () => {
  for (let i = 0; i < 4; i++) {
    allAnswers.value[index.value][i] = "";
  }
  setAllAnswers(selectedRatio.value);
};

const checkHandler = () => {
  for (let i = 0; i < 4; i++) {
    allAnswers.value[index.value][i] = "";
  }
  for (let i = 0; i < selectedChecked.value.length; i++) {
    const element = selectedChecked.value[i];
    setAllAnswers(element);
  }
};

const next = () => {
  if (index.value === total.value - 1) {
    showToast("已经是最后一题了！");
    return;
  }
  index.value++;
};

const prev = () => {
  if (index.value === 0) {
    showToast("已经是第一题了！");
    return;
  }
  index.value--;
};

const showAnswer = () => {
  console.log(item.value.answer);

  if (item.value.answer.length === 1) {
    selectedRatio.value = item.value.answer;
  } else {
    selectedChecked.value.splice(
      0,
      selectedChecked.value.length,
      ...item.value.answer.split("+")
    );
  }
};

const router = useRouter();

// 处理自测试记录数据
const initSelfRecord = () => {
  selfTestAnswer
    .geBySelfTestId(route.query.selfTestId)
    .then((res) => {
      console.log("Self test answers data:", res.data);

      // 确保数据是有效的
      if (!res.data || !Array.isArray(res.data) || res.data.length === 0) {
        console.error("Invalid or empty data returned from selfTestAnswer API");
        showToast("获取答题记录失败");
        return;
      }

      let recordedAns = res.data;
      allAnswers.value = []; // 清空已有答案

      // 确保复制数据而不是引用
      for (let i = 0; i < recordedAns.length; i++) {
        if (Array.isArray(recordedAns[i])) {
          allAnswers.value.push([...recordedAns[i]]);
        } else {
          // 如果数据不是预期的数组格式，创建空数组
          allAnswers.value.push(["", "", "", ""]);
          console.warn(`Answer at index ${i} is not an array:`, recordedAns[i]);
        }
      }

      console.log("Processed allAnswers:", allAnswers.value);

      for (let i = 0; i < allAnswers.value.length; i++) {
        const element = allAnswers.value[i];
        const arr = element.filter((item) => item != "");

        if (arr.length == 0) {
          questionStatus.value[i] = 0; // 未答题
        } else if (arr.length == 1) {
          const ans = arr[0];
          if (ans == items.value[i].answer) {
            questionStatus.value[i] = 1; // 答对
          } else {
            questionStatus.value[i] = 2; // 答错
          }
        } else {
          const arrToStr = arr.sort().join("+");
          if (arrToStr == items.value[i].answer) {
            questionStatus.value[i] = 1; // 答对
          } else {
            questionStatus.value[i] = 2; // 答错
          }
        }
      }

      // 设置第一题的答案
      if (allAnswers.value.length > 0) {
        const firstAnswers = allAnswers.value[0].filter((a) => a !== "");
        if (items.value[0].answer.length === 1) {
          selectedRatio.value = firstAnswers[0] || "";
        } else {
          selectedChecked.value = firstAnswers;
        }
        console.log(
          "First question answers set:",
          items.value[0].answer.length === 1
            ? selectedRatio.value
            : selectedChecked.value
        );
      }
    })
    .catch((error) => {
      console.error("Error fetching self test answers:", error);
      showToast("获取答题记录失败，请重试");
    });
};

// 初始化逻辑
const init = async () => {
  loading.value = true;
  try {
    const { questionItemId, account, selfTestId } = route.query;

    // 处理自测模式
    if (selfTestId) {
      reviewPage.value = true;
      const res = await selfTest.geBySelfTestId(selfTestId);
      items.value = res.data;
      item.value = items.value[0];
      total.value = items.value.length;

      // 初始化问题状态数组
      questionStatus.value = Array(total.value).fill(0);

      initSelfRecord();
      loading.value = false;
      return;
    }

    // 处理常规考试回顾
    if (!questionItemId || !account) {
      router.push({ path: "/testResult/index" });
      return;
    }

    const res = await zhiZhaoApi.getItem(questionItemId);
    items.value = res.data.result;
    item.value = items.value[0];
    total.value = items.value.length;

    // 初始化问题状态数组
    questionStatus.value = Array(total.value).fill(0);

    const response = await zhiZhaoApi.getMyAnswers(questionItemId, account);
    for (let i = 0; i < total.value; i++) {
      allAnswers.value.push([
        response.data[i][0],
        response.data[i][1],
        response.data[i][2],
        response.data[i][3],
      ]);

      // 设置问题状态
      const answers = [
        response.data[i][0],
        response.data[i][1],
        response.data[i][2],
        response.data[i][3],
      ].filter((a) => a !== "");
      if (answers.length > 0) {
        if (compare(answers, items.value[i].answer)) {
          questionStatus.value[i] = 1; // 答对
        } else {
          questionStatus.value[i] = 2; // 答错
        }
      }
    }

    const ans = allAnswers.value[0].filter((a) => a !== "");
    if (ans.length === 1) {
      selectedRatio.value = ans[0];
    } else {
      selectedChecked.value.splice(0, selectedChecked.length, ...ans);
    }
  } catch (error) {
    console.error(error);
    showToast("加载题目失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 权限判断
feedback.value = store.getters.roles.some((role) =>
  ["teacher", "admin"].includes(role)
);

const isAnswered = (idx) => {
  if (!allAnswers.value[idx]) return false;
  return allAnswers.value[idx].some((a) => a !== "");
};

const isCorrect = (idx) => {
  if (!items.value[idx] || !allAnswers.value[idx]) return false;
  const answer = allAnswers.value[idx].filter((a) => a !== "");
  return compare(answer, items.value[idx].answer);
};

const toggleCheckbox = (value) => {
  const index = selectedChecked.value.indexOf(value);
  if (index === -1) {
    selectedChecked.value.push(value);
  } else {
    selectedChecked.value.splice(index, 1);
  }
  checkHandler();
};

// 生命周期钩子
onMounted(() => {
  init();
});
</script>

<style scoped>
.answer-container {
  padding-bottom: 8vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 5px;
  display: flex;
  flex-direction: column;
}

.center_content {
  flex: 1;
  padding: 5px;
  overflow-y: auto;
}

.question-title {
  line-height: 1.5;
  color: #323233;
}

.option-group {
  width: 95%;
}

.option-item {
  width: 95%;
  margin-top: 10px;
}

.option-item :deep(.van-radio),
.option-item :deep(.van-checkbox) {
  width: 95%;
  padding: 12px;
  background-color: #f8f8f8;
  border-radius: 6px;
}

.option-item :deep(.van-radio__label),
.option-item :deep(.van-checkbox__label) {
  white-space: normal;
  word-break: break-word;
}

.answer-analysis {
  margin-top: 5px;
  padding: 8px;
  background-color: #fff;
  border-radius: 8px;
  color: #666;
  font-size: 14px;
}

.loading-overlay {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 999;
  background: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 8px;
}

/* 题目选择器弹窗样式 */
.question-selector-popup {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.popup-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.legend {
  display: flex;
  justify-content: space-around;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 5px;
}

.legend-box {
  width: 20px;
  height: 20px;
  margin-right: 5px;
  border-radius: 4px;
}

.legend-box.correct {
  background-color: #67c23a;
  border: 1px solid #5daf34;
}

.legend-box.incorrect {
  background-color: #f56c6c;
  border: 1px solid #e74c3c;
}

.legend-box.current {
  background-color: #409eff;
  border: 1px solid #337ecc;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  overflow-y: auto;
  flex: 1;
  padding: 10px 0;
}

.question-box {
  background-color: #f1f1f1;
  border: 1px solid #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  height: 40px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #333;
}

.question-box:active {
  transform: scale(0.95);
}

.question-box.correct {
  background-color: #67c23a;
  border-color: #5daf34;
  color: #fff;
}

.question-box.incorrect {
  background-color: #f56c6c;
  border-color: #e74c3c;
  color: #fff;
}

.question-box.current {
  background-color: #409eff;
  border-color: #337ecc;
  color: #fff;
}

/* ActionBar 样式 */
:deep(.van-action-bar) {
  z-index: 999;
  box-shadow: 0 -2px 10px rgba(0, 114, 255, 0.1);
  background-color: #ffffff;
  height: 8vh;
  display: flex;
  align-items: center;
}

:deep(.van-action-bar-icon__icon) {
  transition: all 0.3s ease;
}

:deep(.van-action-bar-icon:active .van-action-bar-icon__icon) {
  transform: scale(1.1);
}

:deep(.prev-button) {
  background-image: linear-gradient(to right, #4facfe, #00f2fe) !important;
  border: none !important;
}

:deep(.next-button) {
  background-image: linear-gradient(to right, #0072ff, #00c6ff) !important;
  border: none !important;
}

:deep(.van-action-bar-icon) {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

:deep(.van-action-bar-button) {
}

:deep(.van-field) {
  padding: 0;
  width: 30px;
}

:deep(.van-field__control) {
  border: 1px solid #e0e0ff;
  border-radius: 4px;
  background-color: #f0f8ff;
  text-align: center;
}

/* 暗黑模式适配 */
@media (prefers-color-scheme: dark) {
  .answer-container {
    background-color: #1a1a1a;
  }

  .option-item :deep(.van-radio),
  .option-item :deep(.van-checkbox) {
    background-color: #2c2c2c;
  }

  .loading-overlay {
    background: rgba(0, 0, 0, 0.7);
  }

  :deep(.van-action-bar) {
    background-color: #1a1a1a;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.2);
  }

  :deep(.van-field__control) {
    background-color: #2c2c2c;
    border-color: #3a3a3a;
    color: #fff;
  }

  .question-box {
    background-color: #333;
    border-color: #444;
    color: #ddd;
  }

  .question-box.correct {
    background-color: #2e5a34;
    border-color: #226622;
    color: #a3d9a5;
  }

  .question-box.incorrect {
    background-color: #5a2e2e;
    border-color: #662222;
    color: #f1a9a9;
  }

  .question-box.current {
    background-color: #2e4a5a;
    border-color: #224466;
    color: #a9c9f1;
  }

  .popup-title {
    color: #ddd;
  }

  .legend-box.correct {
    background-color: #2e5a34;
    border-color: #226622;
  }

  .legend-box.incorrect {
    background-color: #5a2e2e;
    border-color: #662222;
  }

  .legend-box.current {
    background-color: #2e4a5a;
    border-color: #224466;
  }
}
</style>
